package com.salereport.web.controller;

import com.salereport.web.service.ReportService;
import com.salereport.web.vo.ReportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    ReportService reportService;

    @RequestMapping("")
    public String index(HttpServletRequest request, Model model, boolean isFromUpdate){



        if(isFromUpdate){
            model.addAttribute("msg","更新成功");
        }

        ReportVO report = null;
        List<ReportVO> reports = reportService.read(request);
        if(reports!=null&&reports.size()>0){
            report = reports.get(reports.size()-1);
        }

        if(report==null)report = new ReportVO();
        model.addAttribute("report",report);

        return "index";
    }

    @RequestMapping("update")
    public String update(HttpServletRequest request,ReportVO report, RedirectAttributes redirectAttributes){
        reportService.clear(request);
        List<ReportVO> reportVOS = new ArrayList<>();
        reportVOS.add(report);
        reportService.write(request,reportVOS);
        redirectAttributes.addAttribute("isFromUpdate",true);
        return "redirect:/";
    }

    @RequestMapping("clear")
    public String clear(HttpServletRequest request){
        reportService.clear(request);
        return "redirect:/";
    }

    @RequestMapping("get_report")
    @ResponseBody
    public ReportVO getReport(HttpServletRequest request){

        ReportVO report = null;
        List<ReportVO> reports = reportService.read(request);
        if(reports!=null&&reports.size()>0){
            report = reports.get(reports.size()-1);
        }

        if(report==null)report = new ReportVO();

        return report;
    }

}
